using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Windows.Forms;
using System.Globalization;

namespace Camalon.ColorPicker
{
	/// <summary>
	/// Summary description for HexadecimalUpDown.
	/// </summary>
    [ToolboxItem(false)]
    public class HexadecimalUpDown : System.Windows.Forms.NumericUpDown
	{

		public HexadecimalUpDown()
		{
			// TODO: Add any initialization after the InitComponent call
			this.Hexadecimal = true;
			this.UserEdit = true;
			this.Maximum = 0xFFFFFFFF;
			this.Minimum = 0x00000000;
		}


		protected override void OnLeave(EventArgs e)
		{
			base.OnLeave (e);
			long val = Convert.ToInt64( this.Text, 16 );
			this.Value = val;	
			OnValueChanged( new EventArgs());
		}

		protected override void OnTextBoxKeyDown(object source, KeyEventArgs e)
		{
			if( !this.Hexadecimal) this.Hexadecimal = true;
			base.OnTextBoxKeyDown (source, e);

			if( e.KeyCode == Keys.Return ) 
			{
				long val = Convert.ToInt64( this.Text, 16 );
				this.Value = val;	
			}
		}

		bool			_textChanging;
		string			_oldText		= string.Empty;
		protected override void OnTextBoxTextChanged(object source, EventArgs e)
		{
			if( _textChanging ) return;

			_textChanging = true;

			if(this.Text.Length > 8 )
			{
				this.Text = _oldText;
				base.Select( _oldText.Length,0);
			}
			else if(this.Text.Length == 0 )
			{
				this.Text = _oldText;
				base.Select( 0,1);
			}
			
			_oldText = this.Text.ToUpper(CultureInfo.CurrentCulture);	

			_textChanging = false;

		}

		protected override void OnValueChanged(EventArgs e)
		{
			if( !this.Hexadecimal) this.Hexadecimal = true;
			_textChanging = true;
			long val = (long)this.Value;

			this.Text = val.ToString("X8", null);

			base.OnValueChanged (e);
			_textChanging = false;
		}


		protected override void UpdateEditText()
		{
			_textChanging = true;
			long val = (long)this.Value;
			this.Text= val.ToString("X8", null);
			_textChanging = false;
		}

	}
}
